package com.uetoken.cn.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.MeItemAdapter;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.ConfigBean;
import com.uetoken.cn.bean.LoginBean;
import com.uetoken.cn.bean.MeItemBean;
import com.uetoken.cn.bean.RegisterBean;
import com.uetoken.cn.bean.SignBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.utils.CountDownTimerUtils;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @author 谢杨
 * 注册界面
 */
public class RegisterActivity extends BaseActivity implements WebResponse {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.subTitleTv)
    TextView subTitleTv;
    @BindView(R.id.edt_activity_register_phone)
    EditText mEdtPhone;
    @BindView(R.id.tv_activity_register_get_auth_code)
    TextView mTvGetAuthCode;
    @BindView(R.id.edt_activity_register_input_auth_code)
    EditText mEdtrInputAuthCode;
    @BindView(R.id.edt_activity_register_input_six_to_sixteen_pw)
    EditText mEdtrInputSixToSixteenPw;
    @BindView(R.id.cb_activity_register_agree_or_not)
    CheckBox mCbAgreeOrNot;
    @BindView(R.id.tv_activity_register_service_agreement)
    TextView mTvServiceAgreement;
    @BindView(R.id.tv_activity_register_privacy_statement)
    TextView mTvPrivacyStatement;
    @BindView(R.id.tv_activity_register)
    TextView mTvActivityRegister;
    @BindView(R.id.existUEAccountBindTv)
    TextView existUEAccountBindTv;
    private CountDownTimerUtils countDownTimerUtils;
    /**
     * 发送短信请求的网络请求码
     */
    public static final int REQUEST_NETWORK_SMS = 10;
    /**
     * 注册时的网络请求码
     */
    public static final int REQUEST_NETWORK_REGISTER = 20;
    /**
     * 请求登录接口的请求码
     */
    private static final int REQUEST_NETWORK_LOGIN = 30;
    /**
     * 请求签到接口的请求码
     */
    private static final int REQUEST_NETWORK_SIGN = 40;
    /**
     * 服务条例url
     */
    private String serviceAgreementUrl;
    /**
     * 隐私声明Url
     */
    private String privacyStatementUrl;

    /**
     * 验证码
     */

    /**
     * 第三方账号登录类型：0=UE,1-QQ、2-微信、3-微博、4-Pcn、5-优谷
     */
    private int opentype = 0;
    /**
     * 经度
     */
    private String longitude = "0";
    /**
     * 纬度
     */
    private String latitude = "0";
    /**
     * 第三方账号id
     */
    private String uid = "";
    private String phone = "";
    private String authCode = "";
    private String pwd = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        opentype = getIntent().getIntExtra("opentype", 0);
        longitude = getIntent().getStringExtra("longitude");
        latitude = getIntent().getStringExtra("latitude");
        uid = getIntent().getStringExtra("uid");
        if (opentype != 0) {
            mTvTitle.setText(R.string.str_binding);
            subTitleTv.setText(R.string.str_binding_mobile);
            mTvActivityRegister.setText(R.string.str_binding);
            mIvBack.setVisibility(View.VISIBLE);
            existUEAccountBindTv.setVisibility(View.VISIBLE);
        } else {
            mTvTitle.setText(getResources().getString(R.string.str_reigster));
        }
    }

    @Override
    public void initData() {
        String config = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_OTHER_INFO).getString(Constant.SP_CONFIG_INFO, "");
        ConfigBean.DataBean dataBean = new Gson().fromJson(config, ConfigBean.DataBean.class);
        serviceAgreementUrl = new String(EncodeUtils.base64Decode(dataBean.getRegprotocol1()));
        privacyStatementUrl = new String(EncodeUtils.base64Decode(dataBean.getRegprotocol2()));
        LogUtils.e(serviceAgreementUrl, privacyStatementUrl);
    }

    @Override
    public void init() {

    }


    @OnClick({R.id.existUEAccountBindTv, R.id.iv_back, R.id.tv_activity_register_get_auth_code, R.id.tv_activity_register_service_agreement, R.id.tv_activity_register_privacy_statement, R.id
            .tv_activity_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_activity_register_get_auth_code:
                getAuthCode();
                break;
            case R.id.tv_activity_register_service_agreement:
                toWebActivity(serviceAgreementUrl);
                break;
            case R.id.tv_activity_register_privacy_statement:
                toWebActivity(privacyStatementUrl);
                break;
            case R.id.tv_activity_register:
                beginRegister();
                break;
            case R.id.existUEAccountBindTv:
                toBindAndLoginActivity();
                break;
        }
    }

    /**
     * 跳转WebActivity
     */
    private void toWebActivity(String url) {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.TO_WEBVIEW_URL, url);
        startActivity(intent);
    }

    /**
     * 跳转BindAndLoginActivity
     */
    private void toBindAndLoginActivity() {
        Intent intent = new Intent(this, BindAndLoginActivity.class);
        intent.putExtra("opentype", opentype);
        intent.putExtra("longitude", longitude);
        intent.putExtra("latitude", latitude);
        intent.putExtra("uid", uid);
        startActivity(intent);
    }

    /**
     * 获取验证码
     */
    private void getAuthCode() {
        phone = mEdtPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        countDownTimerUtils = new CountDownTimerUtils(this, mTvGetAuthCode, 60000, 1000);
        countDownTimerUtils.start();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getSendSMSUrl(), REQUEST_NETWORK_SMS, Params.getSmsParams(phone));
    }

    /**
     * 开始注册
     */
    private void beginRegister() {
        phone = mEdtPhone.getText().toString();
        authCode = mEdtrInputAuthCode.getText().toString();
        pwd = mEdtrInputSixToSixteenPw.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_be_empty));
            return;
        }
        if (!RegexUtils.isMobileSimple(phone)) {
            ToastUtils.showShort(getResources().getString(R.string.str_phone_not_specification));
            return;
        }
        if (TextUtils.isEmpty(authCode)) {
            ToastUtils.showShort(getResources().getString(R.string.str_auth_code_not_empty));
            return;
        }
        if (pwd.length() < 6 || pwd.length() > 16) {
            ToastUtils.showShort(getResources().getString(R.string.str_pwd_not_specification));
            return;
        }
        if (!mCbAgreeOrNot.isChecked()) {
            ToastUtils.showShort(getResources().getString(R.string.str_please_check_agreement_and_statement));
            return;
        }
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getRegisterAccountUrl(),
                REQUEST_NETWORK_REGISTER,
                Params.getRegisterParams(phone, EncodeUtils.base64Encode2String(pwd.getBytes()), authCode, "", opentype + "", uid));
    }

    /**
     * 登录
     */
    private void Login() {
        LogUtils.dTag("RegisterActivity==", "RegisterActivity== Login phone = " + phone + " pwd = " + pwd);
        OkHttpUtils.getInstance().getStringWithParam(RegisterActivity.this, ApiHelper.getLoginUrl(), REQUEST_NETWORK_LOGIN,
                Params.getLoginParams(phone, EncodeUtils.base64Encode2String(pwd.getBytes()), "0"));
    }

    /**
     * 开始签到
     */
    private void beginSign() {
        OkHttpUtils.getInstance().getStringWithParam(RegisterActivity.this, ApiHelper.getUserSignUrl(), REQUEST_NETWORK_SIGN,
                Params.getUserSignParams(longitude, latitude));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimerUtils != null) {
            countDownTimerUtils.cancel();
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag("RegisterActivity==", "RegisterActivity== requestCode = " + requestCode + " response = " + response);
        switch (requestCode) {
            case REQUEST_NETWORK_SMS:
              /*  JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                ToastUtils.showShort(jsonObject.get("message").getAsString());*/
                break;
            case REQUEST_NETWORK_REGISTER:
                RegisterBean registerBean = new Gson().fromJson(response, RegisterBean.class);
                if (registerBean.getResult() > 0) {
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_ID, String.valueOf(registerBean.getData().getNodeid()));
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_CODE, registerBean.getData().getNodecode());
//                    ToastUtils.showShort(registerBean.getMessage());
                    Login();
//                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
//                    intent.putExtra("flag", "register");
//                    startActivity(intent);
//                    finish();

                } else {
                    dissmissDialog();
                    ToastUtils.showShort(registerBean.getMessage());
                }
                break;
            case REQUEST_NETWORK_LOGIN:
                dissmissDialog();
                LoginBean loginBean = new Gson().fromJson(response, LoginBean.class);
                if (loginBean.getResult() > 0) {
                    //保存用户nodeId
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_ID, String.valueOf(loginBean.getData().getNodeid()));
                    //保存用户nodeCode
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_CODE, loginBean.getData().getNodecode());
                    //保存用户nodeName
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_NODE_NAME, loginBean.getData().getNodename());
                    //保存用户手机号
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MOBILE_NO, loginBean.getData().getMobileno());
                    //保存用户头像地址
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_HEAD_PHOTO, loginBean.getData().getPic());
                    //保存值为true，代表用户已登录
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_WHETHER_LOGIN, true);
                    //保存是否有支付密码的状态
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.IS_PAY_PWD, loginBean.getData().isIspaypwdnull());
                    //保存最大免密支付金额
                    SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_MAXIMUM_SECRET_AMOUNT, String.valueOf(loginBean.getData().getMaxnotpwd()));

                    beginSign();
                    ActivityUtils.finishActivity(MainActivity.class);
                    startActivity(new Intent(this, MainActivity.class));
                    finish();
                }
                ToastUtils.showShort(loginBean.getMessage());
                break;
            case REQUEST_NETWORK_SIGN:
                //签到接口返回的result=-1时，为冻结状态
                SignBean signBean = new Gson().fromJson(response, SignBean.class);
                if (signBean.getResult() <= 0) {
                    ToastUtils.showShort(signBean.getMessage());
                    if (signBean.getResult() == -1) {
                        SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).put(Constant.SP_WHETHER_LOGIN, false);
                    }
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
        ToastUtils.showShort(e.getMessage());
    }
}
